package com.yy.micro.magic.core.model;

import com.fasterxml.jackson.annotation.JsonIgnore;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.validation.constraints.NotNull;
 /**
   * @author YY
   * @version 1.0.0
   * @update 2021/9/22 9:32 下午
   * @description: 数据变换计划。
 */
public class PlanSchedule {
     /**
      * 数据变换任务code，唯一标识。用于区分不同的数据变换任务
      */
    private String planCode;
     /**
      * 版本，当同一个planCode有多个版本时，取最大版本。
      */
    private double version;
     /**
      * 任务描述。
      */
    private String description;
     /**
      * 数据变换任务Rule描述。
      */
    private List<RuleDescriptor> rules;

    public String getPlanCode() {
        return planCode;
    }

    public void setPlanCode(final String planCode) {
        this.planCode = planCode;
    }

    public double getVersion() {
        return version;
    }

    public void setVersion(final double version) {
        this.version = version;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public Map<String, RuleDescriptor> getMapRules() {
        if (null != rules){
            return rules.stream().collect(Collectors.toMap(RuleDescriptor::getKey,RuleDescriptor->RuleDescriptor));
        }
        return null;
    }

    public List<RuleDescriptor> findConventionRules(){
        if (null!= rules && !rules.isEmpty()){
            return rules.stream().filter(r-> !r.isDynamic()).collect(Collectors.toList());
        }
        return null;
    }


    public List<RuleDescriptor> findDynamicRules(String pattern){
        if (null!= rules && !rules.isEmpty() && !StringUtils.isEmpty(pattern)){
            return rules.stream().filter(r->r.isDynamic()&&r.getKey().matches(pattern)).collect(Collectors.toList());
        }
        return null;
    }


    public void setRules(@NotNull List<RuleDescriptor> rules) {
        if (CollectionUtils.isEmpty(this.rules)){
            this.rules = rules;
        }else {
            this.rules.addAll(rules);
        }
    }

    public PlanSchedule addRule(RuleDescriptor descriptor){
        if (CollectionUtils.isEmpty(this.rules)){
            this.rules = new ArrayList<>();
        }
        this.rules.add(descriptor);
        return this;
    }

    @JsonIgnore
    public String getIdentifier(){
        StringBuilder sb = new StringBuilder();
        sb.append(planCode);
        sb.append("-");
        sb.append(version);
        return sb.toString();
    }
}
